#!/bin/bash
cat /dev/null > /etc/ssh/log/vm.log

while true;do
#cat /dev/null > /etc/ssh/log/vm.log
sed '10,$d' /etc/ssh/log/vm.log
vm_name=$(virsh list --all | sed '1,2d' | sed '$d' | grep running | tr -s [:blank:] | cut -f 3 -d ' ')
for line in $vm_name
do
    port=$(virsh dumpxml $line | grep vnc | tr -s [:blank:] | cut -f 4 -d ' ')
    #echo ${port:6:4}
    netstat=$(netstat -ntp | grep ${port:6:4}  | tr -s [:space:] | cut -f 6 -d ' ' | sed '2d')
    #echo $netstat
    if [ "$netstat" = "ESTABLISHED" ];then
        echo "$line is running! ${port:6:4} has established a connection!" >> /etc/ssh/log/vm.log
    else
        echo "$line is running! ${port:6:4} has not established a connection!" >> /etc/ssh/log/vm.log
    fi
done
done

#for((port=5900;port<=5910;port++))
#do
#    netstat=$(netstat -ntp | grep $port  | tr -s [:space:] | cut -f 6 -d ' ' | sed '2d')
#    if [ "$netstat" = "ESTABLISHED" ];then
#        echo "$port has established a connection!"
#        vm_name=$(virsh list --all | sed '1,2d' | sed '$d' | grep running | tr -s [:blank:] | cut -f 3 -d ' ')
#        echo "$vm_name is running!"
#    fi
#done
